package org.frvi.goldspring.web.wicket.form;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.frvi.goldspring.business.entity.Account;
import org.frvi.goldspring.business.service.AccountService;
import org.frvi.goldspring.web.wicket.page.JournalPage;
import org.frvi.goldspring.web.wicket.validator.UniqueAccountNameValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * User: Frank
 * Date: Oct 4, 2009
 * Time: 9:31:00 PM
 */
public class CreateAccountForm extends Form {
    private static Logger log = LoggerFactory.getLogger(CreateAccountForm.class);
    private TextField<String> accountNameField;

    @SpringBean
    private AccountService accountService;

    public CreateAccountForm(String id) {
        super(id);
        add(new FeedbackPanel("feedback"));
        accountNameField = new TextField<String>("name", new Model<String>());
        accountNameField
                .setRequired(true)
                .setLabel(new Model<String>("name"))
                .add(new UniqueAccountNameValidator());
        add(accountNameField);
        add(new Button("create_account_submit_button"));
    }

    @Override
    public void onSubmit() {
        Account account = new Account();
        account.setName(accountNameField.getModelObject());
        // save, and report if name is not unique

        account = accountService.save(account);
        if (log.isDebugEnabled()) {
            log.debug("account name" + account.getName());
            log.debug("account id" + account.getId());
        }
        setResponsePage(new JournalPage(account.getId()));
    }
}
